import subprocess
import os
from tkinter import *
from tkinter import filedialog


def start():
    num = int(e1.get())
    for i in range(num):
        process = subprocess.Popen([f_path])  # 打开".\\simulation\\fmsTestTool.exe"
        pid = process.pid
        print('pid: ', pid)
        pidList.append(pid)
    print('pidList: ', pidList)
    listbox.delete(0, "end")
    for item in pidList:
        listbox.insert("end", item)
    root.mainloop()


def stop():
    pid = listbox.get(listbox.curselection())
    cmd = 'taskkill /pid ' + str(pid) + ' /f'
    try:
        os.system(cmd)
        print(pid, 'killed')
        pidList.remove(pid)
        listbox.delete("active")
        print('pidList: ', pidList)
    except Exception as e:
        print(e)


pidList = []
window = Tk()
window.withdraw()  # 不显示窗口
f_path = filedialog.askopenfilename()
print('\n获取的文件地址：', f_path)
filename = os.path.basename(f_path)
window.destroy()

root = Tk()
root.resizable(False, False)
root.title(f_path)
root.geometry('480x600')
lb1 = Label(root, text=filename)
lb1.place(relx=0, rely=0.05, relwidth=1, relheight=0.05)
e1 = Entry(root)
e1.place(relx=0.45, rely=0.15, relwidth=0.1, relheight=0.05)
btn1 = Button(root, text='运行', command=start)
btn1.place(relx=0.45, rely=0.25, relwidth=0.1, relheight=0.05)
listbox = Listbox(root)
listbox.place(relx=0.3, rely=0.35, relwidth=0.4, relheight=0.5)
btn2 = Button(root, text="停止", command=stop)
btn2.place(relx=0.45, rely=0.9, relwidth=0.1, relheight=0.05)
root.mainloop()